package com.example.lawyer.service;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.example.lawyer.R;
import com.example.lawyer.datavar.OverallData;
import com.example.lawyer.netty.NettyConfig;
import com.example.lawyer.netty.NettyInit;
import com.example.lawyer.netty.NettyStart;
import com.example.lawyer.netty.activityhandler.ActivityMessageCallback;
import com.example.lawyer.netty.data.MessageData;
import com.example.lawyer.netty.data.NettyMessageData;
import com.google.gson.Gson;

import java.util.List;
import java.util.Objects;
import java.util.Random;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyService<T>  extends Service implements ActivityMessageCallback {


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        OverallData overallData = (OverallData) getApplication();
        System.out.println("绑定");
        try {
            new NettyStart().Start(this,overallData);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new MyBindder();
    }


    //收到消息
    @Override
    public void ReceiveMessage(String json) {
        System.out.println("Service收到来自Netty的消息");
        System.out.println(json);
        Gson gson = new Gson();
        NettyMessageData messageData = gson.fromJson(json, NettyMessageData.class);
        if (messageData==null)
        {
            System.out.println("非法消息");
            return;
        }
        ////////////////////////////////////////////////

        if (sendActivityMessage != null) {
            System.out.println("有效回调");

        }



    }

    public class MyBindder extends Binder {
        public NettyService getMyBind() {
            return NettyService.this;
        }

    }

    private SendActivityMessage sendActivityMessage;

    public void SetOnSendActivtyListener(SendActivityMessage sendActivityMessage) {
        this.sendActivityMessage = sendActivityMessage;
    }

    public interface SendActivityMessage {
        void ReceiveMsg(String str,String msgtype);
    }


    @Override
    public void onCreate() {
        Log.i("AAA", "创建");
        System.out.println("创建");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("AAA", "启动");
        System.out.println("启动");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("销毁");
        Log.i("AAA", "销毁");
    }


    //消息通知
    private void RemoteNotice() {
        NotificationChannel channel = null;
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for(int t=0;t<6;t++)
        {
            int i = random.nextInt(9);
            stringBuffer.append(i);
        }

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.item_message_view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel = new NotificationChannel(stringBuffer.toString(), "asdad", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);
            channel.setLightColor(Color.GREEN);
            channel.setShowBadge(false);
        }
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new Notification.Builder(getApplicationContext(), stringBuffer.toString()).setContentTitle("通知栏标题").setContentText("这是消息通过通知栏的内容")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.def_type_icon1)
                    .setColor(Color.parseColor("#FEDA26"))
                    .setTicker("巴士门")
                    .setContent(remoteViews).build();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                notification = new Notification.Builder(getApplicationContext())
                        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.bianji))
                        .setSmallIcon(R.mipmap.def_type_icon1)
                        .setContentTitle("测试")
                        .setContentText("短消息")
                        .setContentIntent(createIntent())
                        .setPriority(Notification.PRIORITY_DEFAULT).build();
            }
        }
        NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannel(channel);
            notificationManager.notify(Integer.parseInt(stringBuffer.toString()), notification);
        }

        if (notificationManager == null) {
            System.out.println("空");
        }
        notificationManager.notify(Integer.parseInt(stringBuffer.toString()), notification);
        System.out.println("完毕");
    }
    private PendingIntent createIntent() {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), Notification.class);
        PendingIntent broadcast = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        return broadcast;
    }
    //判断前后台
    private boolean IsPlatforms()
    {
        boolean isbool = false;
        ActivityManager systemService = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = systemService.getRunningAppProcesses();
        for(ActivityManager.RunningAppProcessInfo appProcessInfo:runningAppProcesses)
        {
            if(appProcessInfo.processName.equals(getApplicationContext().getPackageName()))
            {
                if(appProcessInfo.importance==ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
                {
                    isbool = false;
                    break;
                }else {
                    isbool = true;
                    break;
                }

            }
        }
        return isbool;
    }
}
